home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4691 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.2 KB  |  80 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: pstaite@vnet.ibm.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Derivation and protected members
  5. Date: 31 Jan 1996 15:58:40 GMT
  6. Organization: IBM OS/2 Device Driver Development  Rochester, MN
  7. Message-ID: <4eo3jg$qqc@locutus.rchland.ibm.com>
  8. References: <4el84h$t86@beavis.kronos.com>
  9. Reply-To: pstaite@vnet.ibm.com
  10. NNTP-Posting-Host: warpone.rchland.ibm.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4el84h$t86@beavis.kronos.com>, lipsett@kronos.com (Roger Lipsett) writes:
  14. >Suppose I have a base class, bas, and a derived class, der, of which bas is a
  15. >public base. der has additional data members beyond those provided by bas. All 
  16. >data members of both classes are protected.
  17. >
  18. >I wish to define an operation (=) that will assign an instance of bas to an 
  19. >instance of der by setting all of der's data members that are inherited from 
  20. >bas to the values as provided by the instance of bas, and leaving untouched
  21. >the other data members of der..
  22. >
  23. >There appears to be no simple way to do this. The der-instance does not have
  24. >access to the protected members of the bas-instance, as those members are
  25. >protected. What am I missing here?
  26.  
  27. Why not let the bas class' operator=() do the work for you?  Seems you 
  28. really just want to assign the bas object to the bas portion of a der 
  29. object.  Something like:
  30.  
  31. #include<iostream.h>
  32.  
  33. class bas {
  34.   public:
  35.     bas( int x = 0, int y = 0 ) : n( x ), m( y ) {}
  36.     virtual ~bas() {}
  37.     bas& operator=( const bas& );
  38.     virtual void print() const { cout << "bas: " << n << ' ' << m << endl; }
  39.   protected:
  40.     int n,
  41.         m;
  42. };
  43.  
  44. bas& bas::operator=( const bas& b ) {
  45.     n = b.n;
  46.     m = b.m;
  47.     return *this; }
  48.  
  49.  
  50. class der : public bas {
  51.   public:
  52.     der( int x = 1, int y = 2 ) : bas( x, y ), z( 0 ) {}
  53.     der& operator=( const bas& );
  54.     virtual void print() const { bas::print(); cout << "der: " << z << endl; }
  55.   protected:
  56.     int z;
  57. };
  58.  
  59. der& der::operator=( const bas& b ) {
  60.     bas::operator=( b );
  61.     return *this; }
  62.  
  63.  
  64. int main() {
  65.     bas b( 8, 16 );
  66.     der d( 4, 12 );
  67.     d = b;
  68.     d.print();
  69.     return 0; }
  70.  
  71.  
  72. You should even be able to make bas::operator=() protected if you want 
  73. to restrict access.
  74.  
  75.  
  76.  
  77. Phil Staite, team OS/2
  78. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  79.  
  80.